package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.system.domain.BiddingDemand;
import com.ruoyi.system.domain.HomeMiddleData;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.BiddingDemandService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @Deprecated 用户招标需求业务
 */
@Service
public class BiddingDemandServiceImpl implements BiddingDemandService {
    @Resource
    private BiddingDemandMapper biddingDemandMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private HomeMiddleDataMapper homeMiddleDataMapper;

    @Resource
    private BiddingDemandSelectionMapper biddingDemandSelectionMapper;

    @Resource
    private SysUserOrderMapper sysUserOrderMapper;

    /**
     * @param biddingDemand 招标需求实体类
     * @return 返回查询到的分页结果
     * @Deprecated 查询用户所招标需求
     */
    @Override
    public List<BiddingDemand> selectBiddingDemandList(BiddingDemand biddingDemand) {
        return biddingDemandMapper.selectUserToBiddingDemand(biddingDemand);
    }

    /**
     * @param biddingDemand 招标需求实体类
     * @return 返回查询到的结果
     * @Deprecated 模糊查询用户所招标需求
     */
    @Override
    public List<BiddingDemand> selectLikeBiddingDemandList(BiddingDemand biddingDemand) {
        return biddingDemandMapper.selectUserToBiddingDemand(biddingDemand);
    }

    /**
     * @param biddingDemand 招标需求实体类
     * @param loginUser     当前登录用户信息
     * @return 返回成功或失败的消息
     * @Deprecated 停止我的招标
     */
    @Override
    public AjaxResult stopMyBidding(BiddingDemand biddingDemand, LoginUser loginUser) {
        HashMap<String, Object> checked = checkStatus(biddingDemand.getBiddingDemandId(), loginUser.getUserId(), "stop");
        if (checked != null && !(boolean) checked.get("bool")) {
            return AjaxResult.error((String) checked.get("message"));
        }
        BiddingDemand queryOn = biddingDemandMapper.selectByPrimaryKey(biddingDemand.getBiddingDemandId(), loginUser.getUserId());
        if (queryOn.getStatus().equals("3")) {
            queryOn.setStatus("0");
            // 恢复首页内容
            HomeMiddleData homeMiddleData = homeMiddleDataMapper.queryByDemandId(queryOn.getBiddingDemandId());
            homeMiddleData.setIsDelete("0");
            homeMiddleDataMapper.updateByPrimaryKey(homeMiddleData);
        } else {
            queryOn.setStatus("3");
            // 删除首页信息
            homeMiddleDataMapper.deleteByDemandId(queryOn.getBiddingDemandId());
            // 删除投标人记录表
            biddingDemandMapper.deleteAllByDemandId(queryOn.getBiddingDemandId());
        }
        biddingDemandMapper.updateByPrimaryKey(queryOn);
        return AjaxResult.success("暂停成功!");
    }


    /**
     * @param biddingDemand 招标需求实体类
     * @param loginUser     当前登录用户信息
     * @return 返回成功或失败的消息
     * @Deprecated 添加我的招标
     */
    @Override
    @Transactional
    public AjaxResult addMyBidding(BiddingDemand biddingDemand, LoginUser loginUser) {
        // 非空校验
        if (biddingDemand.getBiddingDemandType() == null || Objects.equals(biddingDemand.getBiddingDemandType(), ""))
            return AjaxResult.error("请选择发布的类型");
        if (biddingDemand.getBiddingDemandName() == null || Objects.equals(biddingDemand.getBiddingDemandName(), ""))
            return AjaxResult.error("请选择发布的类型");
        if (biddingDemand.getBiddingDemandMoney() == null || biddingDemand.getBiddingDemandMoney().compareTo(new BigDecimal(0)) < 0)
            return AjaxResult.error("发布的金额不正确");
        // 判断自己是否存在相同名字的招标
        BiddingDemand queryOn = biddingDemandMapper.selectByPrimaryName(biddingDemand.getBiddingDemandName().replaceAll(" ", ""), loginUser.getUserId());
        if (!ObjectUtils.isEmpty(queryOn))
            return AjaxResult.error("招标计划已存在,无法继续添加!");
        // 执行添加逻辑
        biddingDemand.setUserId(loginUser.getUserId());
        biddingDemand.setCreateBy(loginUser.getUsername());
        biddingDemand.setCreateTime(new Date());
        biddingDemand.setStatus("0");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String[] time = biddingDemand.getTime();
        try {
            biddingDemand.setBiddingDemandStartTime(simpleDateFormat.parse(time[0]));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        try {
            biddingDemand.setBiddingDemandEndTime(simpleDateFormat.parse(time[1]));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        // 判断用户余额是否充足
        SysUser sysUser = sysUserMapper.selectUserById(loginUser.getUserId());
        if (sysUser.getMoney().compareTo(biddingDemand.getBiddingDemandMoney()) < 0) {
            return AjaxResult.error("余额不足,无法发布新的招标需求!");
        }
        // 插入数据库
        biddingDemandMapper.insert(biddingDemand);
        // 修改用户余额
        SysUser user = sysUserMapper.selectUserById(loginUser.getUserId());
        user.setMoney(user.getMoney().subtract(biddingDemand.getBiddingDemandMoney()));
        sysUserMapper.updateUserMoney(user);
        // 查询内容
        BiddingDemand biddingDemand1 = biddingDemandMapper.selectByPrimaryName(biddingDemand.getBiddingDemandName().replaceAll(" ", ""), loginUser.getUserId());
        // 添加首页内容
        HomeMiddleData homeMiddleData = new HomeMiddleData();
        homeMiddleData.setDemand(biddingDemand1.getBiddingDemandName());
        homeMiddleData.setDemandId(Integer.parseInt(biddingDemand1.getBiddingDemandId().toString()));
        homeMiddleData.setType(biddingDemand1.getBiddingDemandType());
        homeMiddleData.setCreateTime(biddingDemand1.getCreateTime());
        homeMiddleData.setIsSticky("0");
        homeMiddleData.setIsDelete("0");
        homeMiddleData.setUserId(loginUser.getUserId());
        homeMiddleDataMapper.insert(homeMiddleData);
        return AjaxResult.success();
    }

    /**
     * @param biddingDemand 招标需求实体类
     * @param loginUser     当前登录用户信息
     * @return 返回成功或失败的消息
     * @Deprecated 删除我的招标
     */
    @Override
    @Transactional
    public AjaxResult deleteMyBidding(BiddingDemand biddingDemand, LoginUser loginUser) {
        // 查询当前招标内容的状态
        HashMap<String, Object> checked = checkStatus(biddingDemand.getBiddingDemandId(), loginUser.getUserId(), "delete");
        if (checked != null && !(boolean) checked.get("bool")) {
            return AjaxResult.error((String) checked.get("message"));
        }
        // 回复用户金额(不是完成的可以恢复 如果是进行中的应当扣除惩罚费用)
        BiddingDemand queryOn = biddingDemandMapper.selectByPrimaryKey(biddingDemand.getBiddingDemandId(), loginUser.getUserId());
        if (!queryOn.getStatus().equals("2") || !queryOn.getStatus().equals("4")) {
            // 修改用户余额
            SysUser user = sysUserMapper.selectUserById(loginUser.getUserId());
            user.setMoney(user.getMoney().add(queryOn.getBiddingDemandMoney()));
            sysUserMapper.updateUserMoney(user);
        }
        // 查询删除招标计划
        biddingDemandMapper.deleteByPrimaryKey(biddingDemand.getBiddingDemandId(), loginUser.getUserId());
        // 删除关联表
        homeMiddleDataMapper.deleteByDemandId(biddingDemand.getBiddingDemandId());
        // 删除关联表
        biddingDemandSelectionMapper.deleteByDemandId(biddingDemand.getBiddingDemandId());
        // 删除关联表
        sysUserOrderMapper.deleteByDemandId(biddingDemand.getBiddingDemandId());
        return AjaxResult.success("删除成功!");
    }

    /**
     * @param biddingDemand 招标需求实体类
     * @param loginUser     当前登录用户信息
     * @return 返回成功或失败的消息
     * @Deprecated 添加我的招标
     */
    @Override
    public AjaxResult editMyBidding(BiddingDemand biddingDemand, LoginUser loginUser) {
        // 非空校验
        if (biddingDemand.getBiddingDemandType() == null || Objects.equals(biddingDemand.getBiddingDemandType(), ""))
            return AjaxResult.error("请选择发布的类型!");
        if (biddingDemand.getBiddingDemandName() == null || Objects.equals(biddingDemand.getBiddingDemandName(), ""))
            return AjaxResult.error("请选择发布的类型!");
        if (biddingDemand.getBiddingDemandMoney() == null || biddingDemand.getBiddingDemandMoney().compareTo(new BigDecimal(0)) < 0)
            return AjaxResult.error("发布的金额不正确!");
        // 查询当前招标内容的状态
        HashMap<String, Object> checked = checkStatus(biddingDemand.getBiddingDemandId(), loginUser.getUserId(), "update");
        if (checked != null && !(boolean) checked.get("bool")) {
            return AjaxResult.error((String) checked.get("message"));
        }
        // 判断自己是否存在相同名字的招标
        BiddingDemand queryOn = biddingDemandMapper.selectByPrimaryName(biddingDemand.getBiddingDemandName().replaceAll(" ", ""), loginUser.getUserId());
        if (!ObjectUtils.isEmpty(queryOn) && !Objects.equals(biddingDemand.getBiddingDemandId(), queryOn.getBiddingDemandId()))
            return AjaxResult.error("招标计划已存在,无法继续添加!");
        // 执行修改逻辑
        biddingDemand.setUserId(loginUser.getUserId());
        biddingDemand.setCreateBy(loginUser.getUsername());
        biddingDemand.setCreateTime(new Date());
        biddingDemand.setUpdateBy(loginUser.getUsername());
        biddingDemand.setUpdateTime(new Date());
        biddingDemand.setStatus("0");
        // 设置开始时间结束时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String[] time = biddingDemand.getTime();
        try {
            biddingDemand.setBiddingDemandStartTime(simpleDateFormat.parse(time[0]));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        try {
            biddingDemand.setBiddingDemandEndTime(simpleDateFormat.parse(time[1]));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        // 判断用户余额是否充足 逻辑是:旧的发布金额 + 自己的金额 < 当前修改的发布金额
        SysUser sysUser = sysUserMapper.selectUserById(loginUser.getUserId());

        if (biddingDemand.getBiddingDemandMoney().compareTo(sysUser.getMoney().add(queryOn.getBiddingDemandMoney())) > 0) {
            return AjaxResult.error("余额不足,无法修改新的招标需求!");
        }


        // 减去用户金额
        if (sysUser.getMoney().compareTo(new BigDecimal("0")) == 0) {
            sysUser.setMoney(queryOn.getBiddingDemandMoney().subtract(biddingDemand.getBiddingDemandMoney()));
        } else if (biddingDemand.getBiddingDemandMoney().compareTo(sysUser.getMoney().add(queryOn.getBiddingDemandMoney())) < 0
                || biddingDemand.getBiddingDemandMoney().compareTo(sysUser.getMoney().add(queryOn.getBiddingDemandMoney())) == 0) {
            sysUser.setMoney(sysUser.getMoney().add(queryOn.getBiddingDemandMoney().subtract(biddingDemand.getBiddingDemandMoney())));
        }

        sysUserMapper.updateUserMoney(sysUser);

        biddingDemandMapper.updateByPrimaryKey(biddingDemand);
        // 删除首页推送表进行二次添加
        homeMiddleDataMapper.deleteByDemandId(queryOn.getBiddingDemandId());
        // 添加首页推送表
        HomeMiddleData homeMiddleData = new HomeMiddleData();
        homeMiddleData.setDemand(biddingDemand.getBiddingDemandName());
        homeMiddleData.setDemandId(Integer.parseInt(biddingDemand.getBiddingDemandId().toString()));
        homeMiddleData.setType(biddingDemand.getBiddingDemandType());
        homeMiddleData.setCreateTime(biddingDemand.getCreateTime());
        homeMiddleData.setIsSticky("0");
        homeMiddleDataMapper.insert(homeMiddleData);
        return AjaxResult.success();
    }


    /**
     * @param id     标书id
     * @param userId 用户id
     * @param type   操作类型
     * @Deprecated 检测招标状态函数
     */
    private HashMap<String, Object> checkStatus(Long id, Long userId, String type) {
        BiddingDemand queryOn = biddingDemandMapper.selectByPrimaryKey(id, userId);
        String status = queryOn.getStatus();
        HashMap<String, Object> hashMap = new HashMap<>();
        if (type.equals("delete")) {
            if (status.equals("2")) {
                hashMap.put("bool", false);
                hashMap.put("message", "当前任务进行中,无法删除否则您会赔偿违约金");
                return hashMap;
            }
        }
        if (type.equals("stop")) {
            if (status.equals("2")) {
                hashMap.put("bool", false);
                hashMap.put("message", "当前任务进行中,无法暂停否则您会赔偿违约金!");
                return hashMap;
            }
        }
        if (type.equals("update")) {
            if (status.equals("2")) {
                hashMap.put("bool", false);
                hashMap.put("message", "当前任务进行中,无法修改否则您会赔偿违约金!");
                return hashMap;
            }
            if (status.equals("1")) {
                hashMap.put("bool", false);
                hashMap.put("message", "当前任务选标中,无法修改请先暂停在进行修改!");
                return hashMap;
            }
        }
        return null;
    }
}
